<?php
/**
 * @version $Id: unocart.php 24 2010-05-21 14:47:16Z vladzimirs $
 * @package UnoCart
 * @copyright Авторские права (C) 2009-2010 UnoCart team & (C) 2007-2010 Joostina team &. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * UnoCart! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл help/copyright.php.
 */
error_reporting(0);
error_reporting(E_ALL);
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');
// 1.5
global $pm_bank, $pm_debit, $pm_paypal, $unocartConfig, $format_currency,
    $array_errors, $ordering_category, $ord_fields_category, $Itemid, $field_ord_category,
    $count_product_select, $defaultItemid, $arr, $array_navigation_steps;
// 1.5
require_once (JPATH_BASE .
    '/administrator/components/com_unocart/unocart.class.php');
require_once (JPATH_BASE . '/components/com_unocart/functions.php');
require_once (JPATH_BASE .
    '/administrator/components/com_unocart/specialtype.php');
$database = &unocartFactory::getDBO();
$unocartConfig = loadConfig();
@session_start();
// Pereviryayu, chy 1 raz zayshly na storinku magazyna, schob pamyataty Itemid
if (!isset($_SESSION['Itemid'])) {
    if ($Itemid = mosGetParam($_REQUEST, "Itemid")) {
        $_SESSION['Itemid'] = $Itemid;
    }
}
$defaultItemid = getDefaultItemid();
$option = mosGetParam($_REQUEST, 'option');
$act = mosGetParam($_REQUEST, 'act', '');
$task = mosGetParam($_POST, 'task', '');
if (!$task)
    $task = mosGetParam($_GET, 'task', '');
$category = mosGetParam($_REQUEST, 'category', '');
$product = mosGetParam($_REQUEST, 'product', '');
$limitstart = intval(mosGetParam($_REQUEST, 'limitstart', 0));
$category_id = intval(mosGetParam($_REQUEST, 'category_id', 0));
$product_id = intval(mosGetParam($_REQUEST, 'product_id'));
$Itemid = mosGetParam($_REQUEST, 'Itemid', 0);
if ($task != 'show_login' && $task != 'login') {
    $_SESSION['back_link'] = $_SERVER['REQUEST_URI'];
}
// ---------------------------------------------------------------------------
// Get the current language and currency
if ($id_currency = mosGetParam($_REQUEST, 'id_currency', '')) {
    $cur = new unocartCurrency($database);
    if ($cur->load($id_currency))
        $_SESSION['currency_id'] = $cur->currency_id;
    $unocartConfig->cur_currency = $cur->currency_id;
    $_SESSION['currency_code'] = $unocartConfig->currency_code = $cur->
        currency_code;
    $_SESSION['currency_value'] = $unocartConfig->currency_value = $cur->
        currency_value;
    $cart = new Cart;
    $cart->refreshCartWithNewCurrency($cur->currency_value);
    // Yakscho budemo povertatysya na tu samu storinku, koly zminyly movu
    if ($back = mosGetParam($_GET, 'back', '')) {
        mosRedirect($back, 0, 1);
    }
    // ------------------------------------------------------------------
} else
    if (!isset($_SESSION['currency_id'])) {
        $_SESSION['currency_id'] = $unocartConfig->mainCurrency;
        $unocartConfig->cur_currency = $unocartConfig->mainCurrency;
        $current_currency = new unocartCurrency($database);
        $current_currency->load($unocartConfig->cur_currency);
        $_SESSION['currency_value'] = $unocartConfig->currency_value = $current_currency->
            currency_value;
        $_SESSION['currency_code'] = $unocartConfig->currency_code = $current_currency->
            currency_code;
    } else {
        $unocartConfig->cur_currency = $_SESSION['currency_id'];
        $unocartConfig->currency_code = $_SESSION['currency_code'];
        $unocartConfig->currency_value = $_SESSION['currency_value'];
    }
    $unocartConfig->cur_lang = Jconfig::getInstance()->config_lang;
if (file_exists($unocartConfig->path . '/lang/' . Jconfig::getInstance()->config_lang . '.php'))
    require_once ($unocartConfig->path . '/lang/' . Jconfig::getInstance()->config_lang . '.php');
else
    require_once ($unocartConfig->path . '/lang/english.php');

// Vytyaguju category_name, product name i t d
if ($act == 'ajax_f') {
    switch ($task) {
        case 'add_to_cart':
            $cart = new Cart;
            $cart->refreshCart(intval(mosGetParam($_REQUEST, 'product_id')), intval(mosGetParam
                ($_REQUEST, 'quantity', 1)), mosGetParam($_REQUEST, 'act'), mosGetParam($_REQUEST,
                'unocart_attr_id'));
            break;
        case 'check_user':
            checkUser(mosGetParam($_GET, 'username'));
            break;
        case 'sendAdmin':
            sendAdminMessage(mosGetParam($_POST, 'product_id'), mosGetParam($_POST,
                'request_message'));
            break;
        case 'deleteData':
            deleteData();
            break;
    }
    return;
}

function getDefaultItemid()
{
    $database = &unocartFactory::getDBO();
    $query = "SELECT menu.id
			  FROM `#__menu` AS menu
			  WHERE menu.link = 'index.php?option=com_unocart' AND menu.published = '1'";
    $database->setQuery($query);
    $Itemid = $database->loadResult();
    return $return = ($Itemid) ? ($Itemid) : ($_SESSION['Itemid']);
}

// -------------------------------------------


function checkUserLogin()
{
    global $my;
    if (!$my->id) {
        mosRedirect(SEFLink('index.php?option=com_unocart&task=show_login', 0, 1));
        exit();
    }
    return 1;
}

function addLinkToProducts(&$products, $category_id = 0)
{
    foreach ($products as $key => $value) {
        $category_id = (!$category_id) ? ($products[$key]->category_id) : ($category_id);
        $products[$key]->product_link = SEFLink('index.php?option=com_unocart&task=product&product_id=' .
            $products[$key]->product_id . '&category_id=' . $category_id);
    }
}

function getMultiplierForCurrency()
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    if ($unocartConfig->cur_currency != $unocartConfig->mainCurrency) {
        $currency = new unocartCurrency($database);
        $currency->load($unocartConfig->cur_currency);
        $multiplier = $currency->currency_value;
    } else {
        $multiplier = 1;
    }
    return $multiplier;
}


function searchChildCategories($category_id, $all_categories, &$cat_search)
{
    foreach ($all_categories as $all_cat) {
        if ($all_cat->category_parent_id == $category_id) {
            searchChildCategories($all_cat->category_id, $all_categories, $cat_search);
            $cat_search[] = $all_cat->category_id;
        }
    }
}


//
function showCheckoutNavigation($step)
{
    if ($step <= 1)
        return;
    global $array_navigation_steps, $unocartConfig;
    $output = array();
    if ($unocartConfig->without_shipping) {
        $array_navigation_steps[4] = $array_navigation_steps[5];
        unset($array_navigation_steps[5]);
    }
    foreach ($array_navigation_steps as $key => $value) {

        // Skip - for payment_method
        if ($key < $step) {
            $output[] = '<a href = "' . SEFLink('index.php?option=com_unocart&amp;task=checkout&amp;step=' .
                $key) . '">' . $value . '</a>';
        } else {
            if ($key == $step)
                $output[] = '<span id = "active_step">' . $value . '</span>';
            else
                $output[] = $value;
        }
    }
    return $output;
}

function sendAdminMessage($product_id, $request_message)
{
    global $my, $unocartConfig;
    $database = &unocartFactory::getDBO();
    $product = new unocartProduct($database);
    $product->load($product_id);
    $price_request = new unocartPriceRequest($database);
    $price_request->bind($_POST);
    $price_request->status = 0;
    $price_request->user_id = $my->id;
    $price_request->request_date = date("Y-m-d H:i:s");
    if (!$price_request->store()) {
        echo $price_request->_db->stderr();
        echo "error";
        die();
    }
    $message = (($my->id) ? (_UNOCART_USERNAME . ": " . $my->username . "\n") : ("")) .
        _UNOCART_NAME_PRODUCT . ": " . $product->getName() . "\n" .
        _UNOCART_NO_PRICE_MESSAGE . ": " . $request_message;

    if (mosMail($unocartConfig->contact_email, $GLOBALS['mosConfig_fromname'], $unocartConfig->
        contact_email, _UNOCART_PRICE_REQUEST, $message)) {
        echo _UNOCART_SEND_MAIL_GOOD;
    } else {
        echo _UNOCART_ERROR_SENDING_MAIL;
    }
    return;
}

// Vytyaguju step
function getStep()
{
    global $my;
    if (!$my->id) {
        return $step = $_SESSION['unocart_step'] = 1;
    } else {
        $step = 2;
    }
    if (!isset($_SESSION['unocart_step']))
        $_SESSION['unocart_step'] = $step;
    if ($step_temp = mosGetParam($_REQUEST, 'step'))
        $step = $step_temp;
    if ($step > 6) {
        mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout', 0, 1));
    }
    return $step_check = checkCorrectStep($step);
}


// Pereviryayu, chy step pravynlyj
function checkCorrectStep($step)
{
    global $unocartConfig;
    $correct_step = $_SESSION['unocart_step'];
    if ($step == $correct_step)
        return $step;
    if (!isset($_SESSION['pm_method']) && $step > 3) {
        mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout', 0, 1));
        exit();
    } else
        if (!isset($_SESSION['sh_pr_method_id']) && $step > 4 && !$unocartConfig->
            without_shipping) {
            mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout', 0, 1));
            exit();
        }
    return $step;
}

// check exist this user
function checkUser($username)
{
    $database = &unocartFactory::getDBO();
    $query = "SELECT user.id
			  FROM `#__users` AS user
			  WHERE user.username = '" . $database->getEscaped($username) . "'";
    $database->setQuery($query);
    $database->query();
    echo ($text = ($database->getNumRows()) ? (htmlentities(sprintf(_UNOCART_USER_EXIST,
        $username))) : ('1'));
    return;
}

function deleteData()
{
    global $unocartConfig, $mainframe;
    $cart = new Cart;
    $cart->getSum();
    saveOrderInfo($cart, 1, $_SESSION['order_hash']);
    $cart->clear();
    deleteSession();
    return;
}

function getAdvInfoUser()
{
    global $my;
    $database = &unocartFactory::getDBO();
    if ($my->id) {
        $adv_user = new unocartUser($database);
        if (!$adv_user->isUserInShop($my->id)) {
            $adv_user->addUserToTableShop($my);
        } else {
            $adv_user = new unocartUser($database);
            $adv_user->load($my->id);
        }
    } else {
        return 0;
    }
    return $adv_user;
}

function showError($error_id)
{
    global $array_errors;
    echo messageOutput($array_errors[$error_id], 'unocart_error');
}

// Function, yaka bude parsyty url
function parseUrl()
{

}

function SEFLink($link, $useDefaultItemId = 0, $redirect = 0)
{
    global $unocartConfig, $defaultItemid;

    $Itemid = ($useDefaultItemId) ? ($defaultItemid) : (mosGetParam($_REQUEST,
        'Itemid'));
    $task = mosGetParam($_REQUEST, 'task', '');
    $arr_no_itemid = array('checkout', 'register', 'add_to_cart', 'search');
    if (in_array($task, $arr_no_itemid))
        $Itemid = $defaultItemid;
    if (!$Itemid) {
        $Itemid = $defaultItemid = getDefaultItemid();
    }
    if ($link == "index.php")
        $link .= '?Itemid=' . $Itemid;
    else
        $link .= '&Itemid=' . $Itemid;
    $link = sefRelToAbs($link);
    return $link;
}

function getCountLanguages()
{
    $database = &unocartFactory::getDBO();
    $query = "SELECT COUNT(a.language_id)
			  FROM `#__unocart_languages` AS a
			  WHERE a.language_publish = '1'";
    $database->setQuery($query);
    return $database->loadResult();
}

function setMetaData($title, $keyword, $description)
{
    global $mainframe;
    $mainframe->setPageTitle($title);
    $mainframe->addMetaTag('description', $description);
    $mainframe->appendMetaTag('keywords', $keyword);
}


function getCategoryIdFromMenu()
{
    global $mainframe;
    $Itemid = mosGetParam($_REQUEST, 'Itemid', '');
    if ($Itemid > 0 && $Itemid != 99999999) {
        $menu = $mainframe->get('menu');
        $params = new mosParameters($menu->params);
        $category_id = $params->get('category_id');
    } else {
        $category_id = 0;
    }
    return $category_id;
}

function showCategories($category_id = 0, $limitstart = 0)
{
    global $mainframe, $unocartConfig, $ordering_category, $ord_fields_category, $Itemid,
        $field_ord_category, $count_product_select;
    $database = &unocartFactory::getDBO();
    // Adds parameter handling
    //if (!$category_id) $category_id = getCategoryIdFromMenu();
    if ($category_id) {
        $folder = 'category/';
        $smarty = smarty_init($folder);
        $category = new unocartCategoryExtend($database);
        $category->load($category_id);
        $template = $category->category_template;
        $unocartConfig->count_products_to_page = $category->products_page;
        $category->getExtendsData();
        $task = mosGetParam($_REQUEST, 'task', '');
        $orderby = mosGetParam($_REQUEST, 'orderby');
        $order = ($order = mosGetParam($_REQUEST, 'order')) ? ($order) : ($category->
            products_sorting);
        $limit = intval(($limit = mosGetParam($_REQUEST, 'limit')) ? ($limit) : ($category->
            products_page));
        $orderby = mosGetParam($_REQUEST, 'orderby', 0);
        if ($orderby) {
            $orderbyq = "DESC";
            $image_arr = 'arrow_down.gif';
        } else {
            $orderbyq = "ASC";
            $image_arr = 'arrow_up.gif';
        }

        // When pathway not used this row can comment for less query to database

        if ($task == 'categories') {
            appendExtendPathWay($category->getTreeChild(), 'category');
        }
        setMetaData($category->category_meta_title, $category->category_meta_keyword, $category->
            category_meta_description);
        // Vytyaguju produkty, yakscho ce ne samyi pershyi rivern
        $total = $category->getCountProducts();
        $action = SEFLink("index.php?option=com_unocart&task=categories&category_id=" .
            $category_id);

        if ($total) {
            $link = "index.php?option=com_unocart&task=categories&category_id=" . $category_id .
                "&Itemid=" . $Itemid;
            $link_limit = $link . "&order=" . $order . "&orderby=" . $orderby;
        }
        // Formuvaty, chy ni ryadok navigation
        if ($total > $limit) {
            $products = $category->getProducts(1, $ord_fields_category[$order], $orderbyq, $ord_fields_category[$category->
                products_sorting2], $orderbyq, $limitstart, $limit);
            require_once (JPATH_BASE . "/includes/pageNavigation.php");
            $pageNav = new mosPageNav($total, $limitstart, $limit);
            $pagenav = $pageNav->writePagesLinks($link_limit);
            $show_pagenav = 1;
        } else {
            $products = $category->getProducts(2, $ord_fields_category[$order], $orderbyq, $ord_fields_category[$category->
                products_sorting2], $orderbyq);
            $pagenav = '';
            $show_pagenav = 0;
        }

        if ($total) {
            addLinkToProducts($products, $category_id);
            // Work with products
            $smarty->assign('navigation_products', $pagenav);
            $smarty->assign('lists_prod', $products);
            $smarty->assign('count_product_to_row', $category->products_row);
            $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
        }
        // End work with products

    } else {
        // Yakscho golovna storinka shopa - vyvodshu inshyi template
        $query = "SELECT main_page.*
				  FROM `#__unocart_config_main_page` AS main_page
				  WHERE main_page.language = '" . $unocartConfig->cur_lang . "'";
        $database->setQuery($query);
        $database->loadObject($row);
        if (!$row) {
            $row->meta_title = $row->meta_keyword = $row->meta_description = $row->
                description = '';
        }
        setMetaData($row->meta_title, $row->meta_keyword, $row->meta_description);
        $template = 'main_page.tpl';
        $pagenav = '';
        $smarty = smarty_init();
        $smarty->assign('info_shop', $row->description);
        $category->category_name = '';
        $category->category_ordertype = 1;
        $total = 0;
    }
    // Vytyaguju categories, dochirni do danoi
    $orderfield = ($category->category_ordertype == 1) ? ("ordering") : ("name");
    $cat = new unocartCategory($database);

    $cat->load($category_id);
    $categories = $cat->getChildCategories($orderfield, 'asc', $publish = 1);
    if (count($categories)) {
        foreach ($categories as $key => $value)
            $categories[$key]->category_link = SEFLink('index.php?option=com_unocart&task=categories&category_id=' .
                $categories[$key]->category_id);
    }

    if ($total) {
        // Generate row with sorting select & count select
        foreach ($field_ord_category as $key => $value) {
            $sorts[] = mosHTML::makeOption($key, $value, 'sort_id', 'sort_value');
        }
        searchValue($category->products_page, $count_product_select);
        foreach ($count_product_select as $key => $value) {
            $product_count[] = mosHTML::makeOption($key, $value, 'count_id', 'count_value');
        }
        $sorting = mosHTML::selectList($sorts, 'order',
            'id = "sort_products" class = "inputbox" size = "1" onchange = "changeSortCountProducts(0)"',
            'sort_id', 'sort_value', $order);
        $product_count = mosHTML::selectList($product_count, 'limit',
            'id = "limit_products" class = "inputbox" size = "1" onchange = "changeSortCountProducts(0)"',
            'count_id', 'count_value', $limit);
        // -----------------------------------------------
        $smarty->assign('product_count', $product_count);
        $smarty->assign('sorting', $sorting);
        $smarty->assign('image_arr', $image_arr);
        $smarty->assign('action', $action);
        $smarty->assign('orderby', $orderby);
    }
    $smarty->assign('action_cart', SEFLink('index.php?option=com_unocart&task=cart'));
    $smarty->assign('image_category_path', $unocartConfig->image_category_live_path);
    $smarty->assign('image_path', $unocartConfig->live_path . '/images');
    $smarty->assign('no_image', 'no_image.gif');
    $smarty->assign('lists_categ', $categories);
    $smarty->assign('count_category_to_row', $unocartConfig->count_category_to_row);
    $smarty->assign('name_categ', $category->category_name);
    // End work with list categories
    $smarty->display($template);
}

function getImagePathway()
{
    // Cej kusok kodu vytyagnutyj z failu includes/pathway.php
    global $mainframe, $mosConfig_live_site, $mosConfig_absolute_path;
    $imgPath = 'templates/' . $mainframe->getTemplate() . '/images/arrow.png';
    if (file_exists("$mosConfig_absolute_path/$imgPath")) {
        $img = '<img src="' . $mosConfig_live_site . '/' . $imgPath .
            '" border="0" alt="arrow" />';
    } else {
        $imgPath = '/images/M_images/arrow.png';
        if (file_exists($mosConfig_absolute_path . $imgPath)) {
            $img = '<img src="' . $mosConfig_live_site .
                '/images/M_images/arrow.png" alt="arrow" />';
        } else {
            $img = '&gt;';
        }
    }
    // end
    return $img;
}

function getEmptyValue($attr_name, $attr_id)
{
    $object->value_price = '';
    $object->attr_name = $attr_name;
    $object->attr_id = $attr_id;
    $object->value_name = _UNOCART_SELECT_VALUE;
    $object->value_id_to_attr_id = 0;
    $object->price_prefix = '';
    return $object;
}

function buildSelectAttributes($attributes)
{
    global $unocartConfig;
    if (!count($attributes))
        return;
    foreach ($attributes as $attr) {
        $array_attr[$attr->attr_id][] = $attr;
    }
    foreach ($array_attr as $key => $value) {
        $attr_type = $value[0]->attr_type;
        foreach ($value as $row) {
            $params['price'] = $row->value_price * $unocartConfig->currency_value;
            if ($attr_type == 1) {
                if ($row->value_price == 0) {
                    $text = $row->value_name;
                } else {
                    $text = $row->value_name . ' (' . $row->price_prefix . format_price($params) .
                        ')';
                }
            } else {
                $text = ($row->image) ? ('<img src = "' . $unocartConfig->live_admin_path .
                    'images/attr/' . $row->image . '" />') : (($row->price_prefix == '=') ? $row->
                    value_name : ($row->value_name . ' (' . $row->price_prefix . format_price($params) .
                    ')'));
            }
            $options[$key][] = mosHTML::makeOption($row->value_id, $text, 'attr_value_id',
                'attr_value_name');
        }
        if ($attr_type == 1) {
            $selects[$key]->selects = mosHTML::selectList($options[$key], 'unocart_attr_id[' .
                $value[0]->attr_id . ']', 'class = "inputbox" size = "1"', 'attr_value_id',
                'attr_value_name');
            $selects[$key]->attr_name = $value[0]->attr_name;
        } else {
            $selects[$key]->selects = mosHTML::radioList($options[$key], 'unocart_attr_id[' .
                $value[0]->attr_id . ']', '', $value[0]->value_id, 'attr_value_id',
                'attr_value_name');
            $selects[$key]->attr_name = $value[0]->attr_name;
        }
    }
    return $selects;
}

function showProduct($product_id, $category_id)
{
    global $unocartConfig, $mainframe, $Itemid, $my;
    $database = &unocartFactory::getDBO();
    $product = new unocartProductExtend($database);
    $product->load($product_id);
    $product->getExtendsData();
    $product->special_type = $product->getSpecialType();
    $attributes = buildSelectAttributes($product->getAttributes());

    $product->getTax();

    // Review
    if (($allow_review = unocartReview::getAllowReview()) > 0) {
        $arr_marks = array();
        $arr_marks[] = mosHTML::makeOption(0, _UNOCART_NOT, 'mark_id', 'mark_value');
        for ($i = 1; $i <= $unocartConfig->max_mark; $i++) {
            $arr_marks[] = mosHTML::makeOption($i, $i, 'mark_id', 'mark_value');
        }
        $text_review = '';
        $select_review = mosHTML::selectList($arr_marks, 'mark',
            'class = "inputbox" size = "1"', 'mark_id', 'mark_value');
    } else {
        $select_review = '';
        $text_review = unocartReview::getText();
    }
    // End Review


    // When pathway not used this row can comment for less query to database
    $category = new unocartCategoryExtend($database);
    $category->load($category_id);
    $category->getName();

    appendExtendPathway($category->getTreeChild(), 'product');

    // ---------------------------------------------------------------------

    $product->can_demo_download = (file_exists($unocartConfig->files_path . $product->
        product_download_file) && $product->product_download_file) ? (1) : (0);
    appendPathWay($product->product_name);
    setMetaData($product->product_meta_title, $product->product_meta_keyword, $product->
        product_meta_description);
    $folder = 'product/';
    $smarty = smarty_init($folder);
    if (is_array($product->product_add_prices)) {
        $product->product_add_prices = array_reverse($product->product_add_prices);
    }
    $smarty->assign('alt_main_image', $product->product_name);
    $smarty->assign('image_path', $unocartConfig->live_path . '/images');
    $smarty->assign('other_files_path', $unocartConfig->live_path . '/other_files');
    $smarty->assign('no_image', 'no_image.gif');
    $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
    $smarty->assign('video_product_path', $unocartConfig->video_product_live_path);
    $smarty->assign('video_image_preview_path', $unocartConfig->
        video_product_live_path . "/preview/");
    $smarty->assign('product', $product);
    $smarty->assign('images', $product->getImages());
    $smarty->assign('videos', $videos = $product->getVideos());
    $smarty->assign('count_videos', count($videos));
    $smarty->assign('attributes', $attributes);
    $product->addLinkToRelatedProducts();
    $smarty->assign('Itemid', $Itemid);
    $smarty->assign('related_prod', $product->product_related);
    $smarty->assign('count_related_prod', $product->product_count_related);
    $smarty->assign('path_to_image', $unocartConfig->live_path . 'images/');
    $smarty->assign('live_path', JPATH_SITE);
    $smarty->assign('enable_wishlist', $unocartConfig->enable_wishlist);
    $smarty->assign('action', SEFLink('index.php?option=com_unocart&task=cart'));
    $smarty->assign('reviews', $product->getReviews());
    $smarty->assign('average_rating', $product->getAverageRating());
    $smarty->assign('allow_review', $allow_review);
    $smarty->assign('select_review', $select_review);
    $smarty->assign('user', $my);
    $smarty->display($template = $product->product_template);
}

function getInfoMainPage()
{
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $query = "SELECT *
			  FROM `#__unocart_config_main_page` AS main_page
			  WHERE main_page.language = '" . Jconfig::getInstance()->config_lang . "'";
    $database->setQuery($query);
    $database->loadObject($row);
    return $row;
}

function showCart()
{
    global $unocartConfig, $mainframe;
    $database = &unocartFactory::getDBO();
    $refresh = mosGetParam($_POST, 'refresh', 0);
    $task2 = mosGetParam($_GET, 'task2');
    $cart = new Cart;
    if ($task2 == 'delete') {
        $cart->delete(intval(mosGetParam($_GET, 'number_id')));
    }
    if ($refresh) {
        $cart->refresh(mosGetParam($_POST, 'quantity', ''));
    } else {
        $cart->getSum();
    }
    $smarty = smarty_init($folder = '');
    $cart->addLinkToProducts(1);
    appendPathWay(_UNOCART_CART);
    $smarty->assign('products', $cart->products);
    $smarty->assign('summ', $cart->summ);
    $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
    $smarty->assign('image_path', $unocartConfig->live_path);
    $smarty->assign('no_image', 'no_image.gif');
    $smarty->assign('href_shop', SEFLink('index.php?option=com_unocart'));
    $smarty->assign('href_checkout', SEFLink('index.php?option=com_unocart&task=checkout'));
    $smarty->assign('rabatt_summ', $cart->rabatt_summ);
    $smarty->assign('use_rabatt', $unocartConfig->use_rabatt_code);
    $smarty->assign('tax_summ', $cart->getTax());
    $smarty->assign('array_tax', $cart->getDifferentTax());
    $smarty->display($template = 'cart.tpl');
}

function showSmallCart($step)
{
    global $unocartConfig, $mainframe;
    $database = &unocartFactory::getDBO();
    if ($step == 1) {
        showCart();
        return;
    }
    $refresh = intval(mosGetParam($_POST, 'refresh', 0));
    $cart = new Cart;
    if ($refresh) {
        $cart->refresh(mosGetParam($_POST, 'quantity', ''));
    } else {
        $cart->getSum();
    }

    $smarty = smarty_init($folder = '');
    $cart->addLinkToProducts();
    $smarty->assign('products', $cart->products);
    $smarty->assign('summ', $cart->summ);
    $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
    $smarty->assign('image_path', $unocartConfig->live_path);
    $smarty->assign('no_image', 'no_image.gif');
    $smarty->assign('rabatt_summ', $cart->rabatt_summ);
    $smarty->assign('tax_summ', $cart->getTax());
    $smarty->assign('array_tax', $cart->getDifferentTax());
    $smarty->assign('step', $step);
    if ($step == 5) {
        $smarty->assign('summ_delivery', $_SESSION['unocart_price_shipping']);
    }
    $smarty->display($template = 'small_cart.tpl');
}

function showWishList()
{
    global $unocartConfig, $mainframe;
    $database = &unocartFactory::getDBO();
    $wishlist = new unocartWishlist($database);
    $smarty = smarty_init($folder = '');
    $wishlist->addLinkToProducts();
    appendPathWay(_UNOCART_WISHLIST);
    $smarty->assign('products', $wishlist->products);
    $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
    $smarty->assign('image_path', $unocartConfig->live_path);
    $smarty->assign('no_image', 'no_image.gif');
    $smarty->assign('href_shop', SEFLink('index.php?option=com_unocart'));
    $smarty->assign('href_checkout', SEFLink('index.php?option=com_unocart&task=cart'));
    $smarty->display($template = 'wishlist.tpl');
}

function JCheckout()
{
    global $my, $unocartConfig, $mainframe, $arr, $Itemid;
    $database = &unocartFactory::getDBO();
    checkUserLogin();
    appendPathWay(_UNOCART_CHECKOUT);
    $cart = new Cart;
    $cart->getSum();
    $smarty = smarty_init();
    if (intval(mosGetParam($_REQUEST, 'step')) == 7) {
        if (isset($_SESSION['paypal_related_finish'])) {
            $smarty->assign('live_path', $unocartConfig->live_path);
            $smarty->assign('payment_info', '');
            if (intval(mosGetParam($_REQUEST, 'error'))) {
                $output = $smarty->fetch($template = 'finish_cancel.tpl');
            } else {
                $output = $smarty->fetch($template = 'finish_info.tpl');
            }
        }
        unset($_SESSION['paypal_related_finish']);
        echo $output;
        return;
    }

    if ($cart->summ <= 0) {
        mosRedirect(SEFLink('index.php?option=com_unocart&task=error&error=1', 0, 1));
        exit();
    }

    // Obrobka danyh, pereviryayu, chy postupayut iz zapytom dani i yakscho tak, to pyshu ih v sessii
    // Ce zrobleno dlya togo, schoby zapysaty v sessiyu do togo, yak bude vyklykatys funkciya getStep
    $pm_temp = mosGetParam($_REQUEST, 'payment_method');
    if ($pm_temp) {
        $params = mosGetParam($_REQUEST, 'params', '');
        $_SESSION['pm_method'] = $pm_temp;
        if (isset($params[$pm_temp])) {
            $_SESSION['pm_params'] = $params[$pm_temp];
        } else {
            $_SESSION['pm_params'] = '';
        }
    }
    $sh_pr_method_id = mosGetParam($_REQUEST, 'sh_pr_method_id', '');

    if ($sh_pr_method_id)
        $_SESSION['sh_pr_method_id'] = $sh_pr_method_id;
    // ----------------------------------------------------------------------------------------------

    $step = getStep();
    $steps = showCheckoutNavigation($step);
    if ($step < 6) {
        $smarty->assign('steps', $steps);
        echo $steps = $smarty->fetch($template = 'menu_order.tpl');
    }
    $output = '';
    if ($step < 5) {
        $_SESSION['unocart_price_shipping_tax'] = $_SESSION['unocart_price_shipping'] =
            $_SESSION['unocart_price_hsipping_tax_percent'] = '';
    }
    switch ($step) {
        case '2':
            // Tut zrobleno update dlya obnovlennya ciny, koly zaloginymsya
            $cart->refreshCartWithNewCurrency(1);
            // -------------------------------------------------------
            $adv_user = getAdvInfoUser();
            $agb = sprintf(_UNOCART_LINK_AGB, SEFLink('index.php?option=com_unocart&task=content&page=agb'),
                SEFLink('index.php?option=com_unocart&task=content&page=return_policy'));
            $smarty->assign('select', $arr['title']);


            $option_country[] = mosHTML::makeOption(0, _UNOCART_REG_SELECT, 'country_id',
                'country_name');
            $select_countries = mosHTML::selectList(array_merge($option_country,
                unocartCountry::getAllCountries()), 'country',
                'id = "country" class = "inputbox" size = "1"', 'country_id', 'country_name', $adv_user->
                country);

            foreach ($arr['title'] as $key => $value) {
                $option_title[] = mosHTML::makeOption($key, $value, 'title_id', 'title_name');
            }
            $select_titles = mosHTML::selectList($option_title, 'title',
                'class = "inputbox" id = "title"', 'title_id', 'title_name', $adv_user->title);
            $select_d_titles = mosHTML::selectList($option_title, 'd_title',
                'class = "inputbox" id = "d_title"', 'title_id', 'title_name', $adv_user->
                d_title);

            $smarty->assign('select_countries', $select_countries);
            $smarty->assign('select_titles', $select_titles);
            $smarty->assign('select_d_titles', $select_d_titles);

            $smarty->assign('live_path', JPATH_SITE);
            $smarty->assign('adv_user', $adv_user);
            $smarty->assign('agb', $agb);
            $smarty->assign('delivery_adress', $adv_user->delivery_adress);
            $smarty->assign('action', SEFLink('index.php?option=com_unocart&task=checkout&step=3'));
            $smarty->assign('register', 1);
            $smarty->assign('submit_text', _UNOCART_NEXT);
            $output = $smarty->fetch($template = 'adress.tpl');
            break;
        case '3':
            if (count($_POST)) {
                $adv_user = getAdvInfoUser();
                $adv_user->bind($_POST);
                if (!$adv_user->check(1)) {
                    echo "<script> alert('" . html_entity_decode($adv_user->getError()) .
                        "'); window.history.go(-1); </script>\n";
                    exit();
                }
                if (!$adv_user->store()) {
                    echo "<script> alert('" . html_entity_decode(_UNOCART_REGWARN_ERROR_DATABASE) .
                        "'); window.history.go(-1); </script>\n";
                    exit();
                }
            }
            $all_payment_methods = unocartPaymentMethod::getAllPaymentMethods();
            $i = 0;
            foreach ($all_payment_methods as $pm) {
                require_once ($unocartConfig->path . 'payments/' . $pm->payment_class . '.php');
                $paym[$i]->name = $pm->payment_name;
                $paym[$i]->payment_id = $pm->payment_id;
                $paym[$i]->payment_class = $pm->payment_class;
                $paym[$i]->payment_description = $pm->payment_description;
                $paym[$i++]->form = call_user_func(array($pm->payment_class, 'showPaymentForm'));
            }
            $smarty->assign('payment_methods', $paym);
            $smarty->assign('action', SEFLink('index.php?option=com_unocart&task=checkout&step=4'));
            $output = $smarty->fetch($template = 'payments.tpl');
            break;
        case '4':
            if (count($_POST)) {
                $payment_method = (isset($_SESSION['pm_method'])) ? ($_SESSION['pm_method']) : (mosGetParam
                    ($_REQUEST, 'payment_method'));
                $params = mosGetParam($_REQUEST, 'params');
                if (!file_exists($unocartConfig->path . 'payments/' . $payment_method . '.php')) {
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=2',
                        0, 1));
                    exit();
                } else {
                    require_once (($unocartConfig->path . 'payments/' . $payment_method . '.php'));
                    if (!class_exists($payment_method)) {
                        $_SESSION['pm_method'] = '';
                        $_SESSION['pm_params'] = '';
                        mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=2',
                            0, 1));
                        exit();
                    }
                }
                if (!call_user_func(array($payment_method, 'checkPaymentInfo'), @$params[$payment_method])) {
                    $_SESSION['pm_method'] = '';
                    $_SESSION['pm_params'] = '';
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=3',
                        0, 1));
                    exit();
                }
                ;
                $paym_method = new unocartPaymentMethod($database);
                $paym_method->class = $payment_method;
                $_SESSION['payment_method_id'] = $paym_method->getId();
            }

            // Yakscho zamovlennya tovaru bez dostavky
            if (!$unocartConfig->without_shipping) {
                $shippings = unocartShippingMethod::getAllShippingMethodsCountry($id_country =
                    unocartUser::getCountryId($my->id));
                $multiplier = getMultiplierForCurrency();
                foreach ($shippings as $key => $value) {
                    $shippings[$key]->shipping_price = unocartShippingMethodPrice::getPricesWeight($value->
                        sh_pr_method_id, $multiplier, $id_country);
                }

                $smarty->assign('shipping_methods', $shippings);
                $smarty->assign('action', SEFLink('index.php?option=com_unocart&task=checkout&step=5'));
                $output = $smarty->fetch($template = 'shippings.tpl');
                break;
            }
        case '5':
            global $arr;
            $adv_user = getAdvInfoUser();
            if (!$unocartConfig->without_shipping) {
                $shipping_id = mosGetParam($_REQUEST, 'shipping_method', '');
                $shipping_method_price = new unocartShippingMethodPrice($database);
                $shipping_method_price->load(mosGetParam($_REQUEST, 'sh_pr_method_id'));
                if (!$shipping_method_price->sh_pr_method_id) {
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=4', 0, 1));
                    exit();
                }
                if (!$shipping_method_price->isCorrectMethodForCountry(intval($adv_user->
                    country))) {
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=4', 0, 1));
                    exit();
                }
                $multiplier = getMultiplierForCurrency();
                $_SESSION['sh_pr_method_id'] = $sh_pr_method_id;
                $_SESSION['unocart_price_shipping'] = $shipping_method_price->calculateSum($multiplier,
                    $cart);
                $_SESSION['unocart_price_shipping_tax'] = $shipping_method_price->calculateTax($_SESSION['unocart_price_shipping']);
                $_SESSION['unocart_price_shipping_tax_percent'] = $shipping_method_price->
                    getTax();
                $sh_method = new unocartShippingMethod($database);
                $sh_method->load($shipping_method_price->shipping_method_id);
                $_SESSION['shipping_method_id'] = $shipping_method_price->shipping_method_id;
            }
            $smarty->assign('step', 6);

            $pm_method = new unocartPaymentMethod($database);
            $pm_method->load($_SESSION['payment_method_id']);

            $country = new unocartCountry($database);
            $country->load($adv_user->country);
            if ($adv_user->delivery_adress) {
                $delivery_info['f_name'] = $adv_user->d_f_name;
                $delivery_info['l_name'] = $adv_user->d_l_name;
                $delivery_info['street'] = $adv_user->d_street;
                $delivery_info['zip'] = $adv_user->d_zip;
                $delivery_info['state'] = $adv_user->d_state;
                $delivery_info['country'] = $country->country_name;
            } else {
                $delivery_info['f_name'] = $adv_user->f_name;
                $delivery_info['l_name'] = $adv_user->l_name;
                $delivery_info['street'] = $adv_user->street;
                $delivery_info['zip'] = $adv_user->zip;
                $delivery_info['state'] = $adv_user->state;
                $delivery_info['country'] = $country->country_name;
            }
            $smarty->assign('sh_method', $sh_method = (!$unocartConfig->without_shipping) ?
                ($sh_method) : (''));
            $smarty->assign('payment_name', $pm_method->payment_name);
            $smarty->assign('delivery_info', $delivery_info);
            $smarty->assign('action', SEFLink('index.php?option=com_unocart&task=checkout&step=6'));


            // Paypal related
            if ($pm_method->payment_type == 2) {
                if (!file_exists($unocartConfig->path . 'payments/' . $pm_method->payment_class .
                    '.php')) {
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=2',
                        0, 1));
                    exit();
                } else {
                    require_once ($unocartConfig->path . 'payments/' . $pm_method->payment_class .
                        '.php');
                }

                if (!class_exists($pm_method->payment_class)) {
                    $_SESSION['pm_method'] = '';
                    $_SESSION['pm_params'] = '';
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=2',
                        0, 1));
                    exit();
                }
                $order_hash = md5(uniqid(rand(), true));
                $_SESSION['order_hash'] = $order_hash;
                if (($ret = call_user_func(array($pm_method->payment_class, 'showEndForm'), $pm_method->
                    payment_params, $order_hash)) === 0) {
                    $_SESSION['pm_method'] = '';
                    $_SESSION['pm_params'] = '';
                    mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=3',
                        0, 1));
                    exit();
                } else {

                }
                $paypal_related = 1;
                $_SESSION['paypal_related_finish'] = 1;
                $smarty->assign('payment_form', $ret);
            } else {
                $paypal_related = 0;
            }
            $smarty->assign('paypal_related', $paypal_related);
            $output = $smarty->fetch($template = 'finish.tpl');
            break;
        case '6':
            // if error
            saveOrderInfo($cart, 0);
            $smarty->assign('live_path', $unocartConfig->live_path);
            $smarty->assign('payment_info', '');
            $output = $smarty->fetch($template = 'finish_info.tpl');
            break;
    }
    if ($step > 1 && $step < 6)
        showSmallCart($step);
    echo $output;
}

function saveOrderInfo($cart, $paypal_related, $order_hash = null)
{
    global $database, $unocartConfig, $arr;
    $smarty = smarty_init();
    $payment_method = $_SESSION['pm_method'];
    $pm_method = new unocartPaymentMethod($database);
    $pm_method->load($_SESSION['payment_method_id']);
    if (!file_exists($unocartConfig->path . 'payments/' . $payment_method . '.php')) {
        mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=2',
            0, 1));
        exit();
    } else {
        require_once ($unocartConfig->path . 'payments/' . $payment_method . '.php');
    }

    if (!class_exists($payment_method)) {
        $_SESSION['pm_method'] = '';
        $_SESSION['pm_params'] = '';
        mosRedirect(SEFLink('index.php?option=com_unocart&task=checkout&step=3&error=2',
            0, 1));
        exit();
    }

    $order = new unocartOrder($database);
    $adv_user = getAdvInfoUser();
    $arr_property = array('user_id', 'f_name', 'l_name', 'firma_name', 'email',
        'street', 'zip', 'city', 'state', 'country', 'phone', 'fax', 'title', 'd_f_name',
        'd_l_name', 'd_firma_name', 'd_street', 'd_zip', 'd_city', 'd_state', 'd_phone',
        'd_title');

    foreach ($adv_user as $key => $value) {
        if (in_array($key, $arr_property)) {
            $order->$key = $value;
        }
    }
    $order->order_tax = $cart->getTax();
    $order->order_date = $order->order_m_date = date("Y-m-d H:i:s", mktime());
    $order->order_subtotal = $cart->summ;
    $order->order_shipping = $_SESSION['unocart_price_shipping'];
    $order->order_discount = $cart->rabatt_summ;
    $order->order_total = $order->order_subtotal + $order->order_shipping - $order->
        order_discount;

    $order->order_status = ($paypal_related) ? (1) : ($unocartConfig->
        default_status_order);
    $order->shipping_method_id = ($unocartConfig->without_shipping) ? (0) : $_SESSION['shipping_method_id'];
    $order->payment_method_id = $_SESSION['payment_method_id'];
    if (is_array($_SESSION['pm_params'])) {
        $order->payment_params = replaceArray($_SESSION['pm_params'], call_user_func(array
            ($payment_method, 'getParams')));
    }
    $order->payment_params = _UNOCART_FINISH_PAYMENT_METHOD . ": " . $pm_method->
        payment_name . "\n" . $order->payment_params;
    $order->ip_address = $_SERVER['REMOTE_ADDR'];
    $order->order_add_info = (isset($_SESSION['order_add_info'])) ? ($_SESSION['order_add_info']) : (mosGetParam
        ($_REQUEST, 'order_add_info', ''));
    $order->currency_code = $unocartConfig->currency_code;
    $order->order_number = outputDigit(unocartOrder::getLastOrderId(), 8);
    $order->order_hash = $order_hash;

    $country = new unocartCountry($database);
    $country->load($order->country);
    $order->country = $country->country_name;
    $order->title = $arr['title'][$order->title];
    $order->d_title = ($order->d_title > 0) ? ($arr['title'][$order->d_title]) : (0);
    $order->checkDeliveryData();

    if (!$order->store()) {
        echo $order->getError();
        exit();
    }
    $order_history = new unocartOrderHistory($database);
    $order_history->order_id = $order->order_id;
    $order_history->order_status_id = $order->order_status;
    $order_history->status_date_added = $order->order_date;
    $order_history->customer_notify = 1;
    $order_history->store();

    // Zmunyuyu dani dlya vyvodu na order
    $status = new unocartOrderStatus($database);
    $status->load($order->order_status);
    $order->status = $status->status_name;
    $order->order_date = strftime($unocartConfig->store_date_format, strtotime($order->
        order_date));
    $order->products = $cart->products;
    $order->order_shipping_tax = $_SESSION['unocart_price_shipping_tax'];

    $shippingMethod = new unocartShippingMethod($database);
    $shippingMethod->load($order->shipping_method_id);


    $order->shipping_information = $shippingMethod->shipping_name;
    $order->payment_information = $order->payment_params;
    // End zminy danyh
    $cart->addOrderItem($order->order_id);
    $cart->calcNettoPrice();

    $order->order_shipping_netto = $cart->getShippingNettoPrice();
    $order->netto_sum = $cart->getSumNetto();
    $order->sum = $cart->getSum();
    $order->calcNettoPrice();
    $smarty->assign('order', $order);

    $smarty->assign('config', $unocartConfig);
    $message_client = $smarty->fetch('email_client.tpl');
    $message_admin = $smarty->fetch('email_admin.tpl');
    $order->different_tax = $cart->getDifferentTax();
    require_once (JPATH_BASE . "/components/com_unocart/pdf/pdf.php");
    $order->pdf_file = generatePdf($order, $cart, $unocartConfig);
    $order->insertPDF();

    require_once (JPATH_BASE .
        "/components/com_unocart/mail/multifilemail.class.php");
    $mail = new multiFileMail($unocartConfig->contact_email, $GLOBALS['mosConfig_fromname'],
        $unocartConfig->contact_email, _UNOCART_NEW_ORDER, $message_admin, Jstring::str_ireplace("charset=",
        "", _ISO));
    $mail->sendMail();

    $mail = new multiFileMail($unocartConfig->contact_email, $GLOBALS['mosConfig_fromname'],
        $adv_user->email, _UNOCART_NEW_ORDER, $message_client, Jstring::str_ireplace("charset=",
        "", _ISO));
    $mail->attachFile($unocartConfig->path . "pdf/files/" . $order->pdf_file);
    $mail->sendMail();

    if (!$paypal_related) {
        $cart->clear();
        deleteSession();
    }
}

function deleteSession()
{
    $_SESSION['check_params'] = $_SESSION['cart'] = $_SESSION['unocart_step'] = $_SESSION['unocart_price_hsipping_tax_percent'] =
        $_SESSION['unocart_price_shipping'] = $_SESSION['unocart_price_shipping_tax'] =
        $_SESSION['pm_method'] = $_SESSION['pm_params'] = $_SESSION['payment_method_id'] =
        $_SESSION['shipping_method_id'] = $_SESSION['unocart_price_shipping_tax_percent'] = null;
}

function JsaveRegistration()
{
    // Spochatku funkciya joomla, de pereviryaju, chy pidhodyat dani pro reestraciju
    global $unocartConfig;
    $database = &unocartFactory::getDBO();
    $default_usergroup = unocartUsergroup::getDefaultUsergroup();
    global $acl;
    global $mosConfig_sitename, $mosConfig_live_site, $mosConfig_useractivation, $mosConfig_allowUserRegistration,
        $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailfrom, $mosConfig_fromname;
    if ($mosConfig_allowUserRegistration == 0) {
        mosNotAuth();
        return;
    }

    // simple spoof check security
    josSpoofCheck();

    // For sumisnosti z clasom mosUser
    $_POST['name'] = mosGetParam($_POST, 'f_name');
    $_POST['username'] = mosGetParam($_POST, 'u_name');
    $row = new unocartUser($database);
    $row2 = new mosUser($database);

    if (!$row->bind($_POST, 'usertype')) {
        mosErrorAlert($row->getError());
    }

    if (!$row2->bind($_POST, 'usertype')) {
        mosErrorAlert($row2->getError());
    }

    $row->f_name = Jstring::trim($row->f_name);
    $row->u_name = Jstring::trim($row->u_name);
    $row->l_name = Jstring::trim($row->l_name);
    $row->email = Jstring::trim($row->email);
    $row->street = Jstring::trim($row->street);
    $row->state = Jstring::trim($row->state);
    $row->phone = Jstring::trim($row->phone);
    $row->fax = Jstring::trim($row->fax);
    $row->title = Jstring::trim($row->title);
    $row->password = Jstring::trim($row->password);
    $row->usergroup_id = $default_usergroup;
    mosMakeHtmlSafe($row);

    $row2->id = 0;
    $row2->usertype = '';
    $row2->gid = $acl->get_group_id('Registered', 'ARO');

    if ($mosConfig_useractivation == 1) {
        $row2->activation = md5(mosMakePassword());
        $row2->block = '1';
    }

    if (!$row->check()) {
        echo "<script> alert('" . html_entity_decode($row->getError()) .
            "'); window.history.go(-1); </script>\n";
        exit();
    }

    $pwd = $row->password;
    $row->password = $row2->password = md5($row->password);
    $row2->registerDate = date('Y-m-d H:i:s');

    if (!$row->store()) {
        echo "<script> alert('" . html_entity_decode($row->getError()) .
            "'); window.history.go(-1); </script>\n";
        exit();
    }

    if (!$row2->store()) {
        $query = "DELETE FROM `#__unocart_users`
						  WHERE `user_id` = '0'";
        $database->setQuery($query);
        $database->query();
        echo "<script> alert('" . html_entity_decode($row->getError()) .
            "'); window.history.go(-1); </script>\n";
        return false;
    }


    $query = "UPDATE `#__unocart_users` AS user
					  SET user.user_id = '" . $row2->id . "'
					  WHERE user.user_id = '0'";
    $database->setQuery($query);
    $database->query();
    $name = Jstring::trim($row2->name);
    $email = Jstring::trim($row->email);
    $username = Jstring::substr(Jstring::trim($row2->username), 0, 25);

    $subject = sprintf(_SEND_SUB, $name, $mosConfig_sitename);
    $subject = html_entity_decode($subject, ENT_QUOTES);

    if ($mosConfig_useractivation == 1) {
        $message = sprintf(_USEND_MSG_ACTIVATE, $name, $mosConfig_sitename, $mosConfig_live_site .
            "/index.php?option=com_registration&task=activate&activation=" . $row2->
            activation, $mosConfig_live_site, $username, $pwd);
    } else {
        $message = sprintf(_USEND_MSG, $name, $mosConfig_sitename, $mosConfig_live_site);
    }

    $message = html_entity_decode($message, ENT_QUOTES);

    // check if Global Config `mailfrom` and `fromname` values exist
    if ($mosConfig_mailfrom != '' && $mosConfig_fromname != '') {
        $adminName2 = $mosConfig_fromname;
        $adminEmail2 = $mosConfig_mailfrom;
    } else {
        // use email address and name of first superadmin for use in email sent to user
        $query = "SELECT name, email" . "\n FROM #__users" . "\n WHERE LOWER( usertype ) = 'superadministrator'" .
            "\n OR LOWER( usertype ) = 'super administrator'";
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        $row2 = $rows[0];

        $adminName2 = $row2->name;
        $adminEmail2 = $row2->email;
    }

    // Send email to user
    mosMail($adminEmail2, $adminName2, $email, $subject, $message);

    // Send notification to all administrators
    $subject2 = sprintf(_SEND_SUB, $name, $mosConfig_sitename);
    $message2 = sprintf(_ASEND_MSG, $adminName2, $mosConfig_sitename, $row->f_name,
        $email, $username);
    $subject2 = html_entity_decode($subject2, ENT_QUOTES);
    $message2 = html_entity_decode($message2, ENT_QUOTES);

    // get email addresses of all admins and superadmins set to recieve system emails
    $query = "SELECT email, sendEmail" . "\n FROM #__users" . "\n WHERE ( gid = 24 OR gid = 25 )" .
        "\n AND sendEmail = 1" . "\n AND block = 0";
    $database->setQuery($query);
    $admins = $database->loadObjectList();

    foreach ($admins as $admin) {
        // send email to admin & super admin set to recieve system emails
        mosMail($adminEmail2, $adminName2, $admin->email, $subject2, $message2);
    }

    if ($mosConfig_useractivation == 1) {
        echo _REG_COMPLETE_ACTIVATE;
    } else {
        echo _REG_COMPLETE;
    }
}

    function JRegister()
    {
        global $mainframe, $arr, $unocartConfig;
        $database = &unocartFactory::getDBO();
        appendPathWay(_UNOCART_REGISTRATION);
        $smarty = smarty_init($folder = '');
        $smarty->assign('selected', mosGetParam($_POST, 'title', 0));
        $option_country[] = mosHTML::makeOption(0, _UNOCART_REG_SELECT, 'country_id',
            'country_name');
        $select_countries = mosHTML::selectList(array_merge($option_country,
            unocartCountry::getAllCountries()), 'country',
            'id = "country" class = "inputbox" size = "1"', 'country_id', 'country_name');

        foreach ($arr['title'] as $key => $value) {
            $option_title[] = mosHTML::makeOption($key, $value, 'title_id', 'title_name');
        }
        $select_titles = mosHTML::selectList($option_title, 'title',
            'class = "inputbox" id = "title"', 'title_id', 'title_name');
        $smarty->assign('select_titles', $select_titles);
        $smarty->assign('select_countries', $select_countries);
        $smarty->assign('live_path', JPATH_SITE);
        $validate = josSpoofValue();
        $smarty->assign('validate', $validate);
        $smarty->display($template = 'register.tpl');
        $cart = new Cart;
        $cart->insertTempCart();
    }

    function showLogin()
    {
        global $unocartConfig;
        $smarty = smarty_init();
        $return_href = (isset($_SERVER['HTTP_REFERER'])) ? ($_SERVER['HTTP_REFERER']) : (SEFLink
            ('index.php?option=com_unocart&task=checkout'));
        $smarty->assign('href_register', SEFLink('index.php?option=com_unocart&task=register'));
        $smarty->assign('href_lost_pass', SEFLInk('index.php?option=com_registration&task=lostPassword'));
        $smarty->assign('return_href', $return_href);
        $smarty->assign('validate', $validate = josSpoofValue(1));
        $smarty->assign('Itemid', mosGetParam($_REQUEST, 'Itemid'));
        $template = 'checkout_n_r.tpl';

        $smarty->display($template);
    }

    function JLogin()
    {
        global $mainframe;
        $database = &unocartFactory::getDBO();
        /** get the information about the current user from the sessions table */
        $mainframe->login();
        $my = $mainframe->getUser();

        // detect first visit
        $mainframe->detect();
        if ($my->id) {
            $_SESSION['unocart_step'] = 2;
        }
        if (isset($_SESSION['back_link'])) {
            mosRedirect(SEFLink($_SESSION['back_link']));
        }
        mosRedirect(mosGetParam($_POST, 'return'));
    }


    function JRabatt($code)
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $rabatt = new unocartRabatt($database);
        $rabatt->code = $code;
        if ($rabatt->check()) {
            $cart = new Cart();
            $cart->setRabatt($rabatt->coupon_type, $rabatt->coupon_value);
            showCart();
        } else {
            echo $rabatt->error;
            exit();
        }
    }


    function JContent($page)
    {
        global $mainframe;
        switch ($page) {
            case 'agb':
                $pathway = _UNOCART_AGB;
                break;
            case 'return_policy':
                $pathway = _UNOCART_RETURN_POLICY;
                break;
        }
        appendPathWay($pathway);
        $content = getInfoMainPage();
        echo $content->$page;
    }

    function JSearch($search, $limitstart)
    {
        global $mainframe, $unocartConfig, $Itemid;
        $database = &unocartFactory::getDBO();
        // Variance joomla 1.0 and 1.5
        // This is for joomla 1.0 and for joomla 1.5 less on 1.5.8 , IN Joomla 1.0.x function mosGetParam add additional slashes
        $search = stripslashes($search);
        // End For joomla 1.0
        $search = Jstring::str_ireplace('\\', '\\\\', $search);
        $search = addcslashes($database->getEscaped($search), "_%");
        appendPathWay('search');
        $query = "SELECT DISTINCT prod.product_id, prod.*, prod_descr.*, (" . $unocartConfig->
            currency_value . " * prod.product_price) AS product_price, pr_cat.category_id
			  FROM `#__unocart_products` AS prod
			  LEFT JOIN `#__unocart_products_description` AS prod_descr USING(product_id)
			  LEFT JOIN `#__unocart_products_to_categories` AS pr_cat USING(product_id)
			  WHERE (LOWER(prod_descr.product_name) LIKE '%" . $search .
            "%' OR LOWER(prod_descr.product_short_description) LIKE '%" . $search .
            "%' OR LOWER(prod_descr.product_description) LIKE '%" . $search .
            "%') AND prod.product_publish = '1'
			  GROUP BY prod.product_id";
        $database->setQuery($query);
        $res = $database->query();
        $total = @intval($database->getNumRows($res));
        if (!$total) {
            echo _UNOCART_NO_SEARCH_RESULTS;
            return;
        }
        $limit = intval(($limit = mosGetParam($_REQUEST, 'limit', 0)) ? ($limit) : ($unocartConfig->
            count_products_to_page));
        // Formuvaty, chy ni ryadok navigation
        if ($total > $limit) {
            $query .= " LIMIT " . $limitstart . ", " . $limit;
            $database->setQuery($query);
            $rows = $database->loadObjectList();
            $link = SEFLink("index.php?option=com_unocart&task=search&option=com_unocart&unocart_search=" .
                $search);
            require_once (JPATH_BASE . "/includes/pageNavigation.php");
            $pageNav = new mosPageNav($total, $limitstart, $limit);
            $pagenav = $pageNav->writePagesLinks($link);
            $show_pagenav = 1;
        } else {
            $database->setQuery($query);
            $rows = $database->loadObjectList();
            $pagenav = '';
            $show_pagenav = 0;
        }
        addLinkToProducts($rows);
        $smarty = smarty_init();
        $smarty->assign('show_pagenav', $show_pagenav);
        $smarty->assign('navigation', $pagenav);
        $smarty->assign('count_product_to_row', $unocartConfig->count_products_to_row);
        $smarty->assign('products', $rows);
        $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
        $smarty->display('search.tpl');
    }

    function JAdvancedSearch($op, $limitstart)
    {
        global $unocartConfig, $Itemid;

        $category_id = intval(mosGetParam($_REQUEST, 'category_id'));
        $manufacturer_id = intval(mosGetParam($_REQUEST, 'manufacturer_id'));
        $date_to = mosGetParam($_REQUEST, 'date_to', '');
        $date_from = mosGetParam($_REQUEST, 'date_from', '');
        $price_to = mosGetParam($_REQUEST, 'price_to', '');
        $price_from = mosGetParam($_REQUEST, 'price_from', '');
        $include_subcat = intval(mosGetParam($_REQUEST, 'include_subcat'));
        if ($op == 'search') {
            $where = array();
            $from = array();

            if (checkMyDate($date_to) && checkMyDate($date_from)) {
                if ($date_to && $date_from) {
                    $where[] = " AND prod.product_date_added > " . $date_from .
                        " AND prod.product_date_added < " . $date_to;
                } else
                    if ($date_to) {
                        $where[] = " AND prod.product_date_added < " . $date_to;
                    } else
                        if ($date_from) {
                            $where[] = " AND prod.product_date_added > " . $date_from;
                        }
            }


            if (intval($price_to) && intval($price_from)) {
                $where[] = " AND prod.product_price > " . $price_from * $unocartConfig->
                    currency_value . " AND prod.product_price < " . $price_to * $unocartConfig->
                    currency_value;
            } else
                if (intval($price_to)) {
                    $where[] = " AND prod.product_price < " . $price_to * $unocartConfig->
                        currency_value;
                } else
                    if (intval($price_from)) {
                        $where[] = " AND prod.product_price > " . $price_from * $unocartConfig->
                            currency_value;
                    }

            if (intval($manufacturer_id)) {
                $from[] = " INNER JOIN `#__unocart_manufacturers` AS manuf ON prod.product_manufacturer_id = manuf.manufacturer_id ";
                $where[] = " AND prod.product_manufacturer_id = '" . intval($manufacturer_id) .
                    "'";
            }

            if ($category_id) {
                if (isset($include_subcat)) {
                    $all_categories = unocartCategory::getAllCategories();
                    $cat_search[] = $category_id;
                    searchChildCategories($category_id, $all_categories, $cat_search);
                    $where_sub_cat = " AND (";
                    foreach ($cat_search as $key => $value) {
                        $where_sub_cat .= "pr_cat.category_id = '" . $value . "' OR ";
                    }
                    $where_sub_cat = Jstring::substr($where_sub_cat, 0, Jstring::strlen($where_sub_cat) - 3);
                    $where_sub_cat .= ' )';
                    $where[] = $where_sub_cat;
                } else {
                    $where[] = " AND pr_cat.category_id = '" . $category_id . "'";
                }
            }
            $where_query = $from_query = '';
            foreach ($where as $wh) {
                $where_query .= $wh;
            }
            foreach ($from as $fr) {
                $from_query .= $fr;
            }
            $database = &unocartFactory::getDBO();
            $search_word = mosGetParam($_REQUEST, 'search_word');
            $search = stripslashes($search_word);
            $search = Jstring::str_ireplace('\\', '\\\\', $search_word);
            $search = addcslashes($database->getEscaped($search), "_%");
            $query = "SELECT DISTINCT prod.product_id, prod.*, prod_descr.*, (" . $unocartConfig->
                currency_value . " * prod.product_price) AS product_price, pr_cat.category_id
				  FROM `#__unocart_products` AS prod
				  LEFT JOIN `#__unocart_products_description` AS prod_descr ON prod.product_id = prod_descr.product_id
				  LEFT JOIN `#__unocart_products_to_categories` AS pr_cat ON pr_cat.product_id = prod.product_id
				  $from_query
				  WHERE (LOWER(prod_descr.product_name) LIKE '%" . $search .
                "%' OR LOWER(prod_descr.product_short_description) LIKE '%" . $search .
                "%' OR LOWER(prod_descr.product_description) LIKE '%" . $search .
                "%') AND prod.product_publish = '1'
				  $where_query
				  GROUP BY prod.product_id";
            $database->setQuery($query);
            $res = $database->query();
            $total = @intval($database->getNumRows($res));
            if (!$total) {
                echo _UNOCART_NO_SEARCH_RESULTS;
                return;
            }
            $limit = intval(($limit = mosGetParam($_REQUEST, 'limit', 0)) ? ($limit) : ($unocartConfig->
                count_products_to_page));
            // Formuvaty, chy ni ryadok navigation
            if ($total > $limit) {
                $query .= " LIMIT " . $limitstart . ", " . $limit;
                $database->setQuery($query);
                $rows = $database->loadObjectList();
                $link = "index.php?option=com_unocart&task=adv_search&option=com_unocart&search_word=" .
                    $search;
                $link .= '&search_word=' . $search . '&op=' . $op . "&Itemid=" . $Itemid;
                $link .= '&category_id=' . $category_id . '&manufacturer_id=' . $manufacturer_id .
                    '&price_to=' . $price_to . '&price_from=' . $price_from . '&date_to=' . $date_to .
                    '&date_from=' . $date_from;
                require_once (JPATH_BASE . "/includes/pageNavigation.php");
                $pageNav = new mosPageNav($total, $limitstart, $limit);
                $pagenav = $pageNav->writePagesLinks($link);
                $show_pagenav = 1;
            } else {
                $database->setQuery($query);
                $rows = $database->loadObjectList();
                $pagenav = '';
                $show_pagenav = 0;
            }

            addLinkToProducts($rows);
            $smarty = smarty_init();
            $smarty->assign('show_pagenav', $show_pagenav);
            $smarty->assign('navigation', $pagenav);
            $smarty->assign('count_product_to_row', $unocartConfig->count_products_to_row);
            $smarty->assign('products', $rows);
            $smarty->assign('Itemid', $Itemid);
            $smarty->assign('no_image', 'no_image.gif');
            $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
            $smarty->display('search.tpl');
        } else {
            includeCalendar();
            $categories = buildTreeCategory(1);
            $first = mosHTML::makeOption(0, _UNOCART_SEARCH_ALL_CATEGORIES, 'category_id',
                'category_name');
            array_unshift($categories, $first);
            $list_categories = mosHTML::selectList($categories, 'category_id',
                'class = "inputbox" size = "1"', 'category_id', 'category_name');

            $first = mosHTML::makeOption(0, _UNOCART_SEARCH_ALL_MANUFACTURERS,
                'manufacturer_id', 'manufacturer_name');
            $manufacturers = unocartManufacturer::getAllManufacturers();
            array_unshift($manufacturers, $first);
            $list_manufacturers = mosHTML::selectList($manufacturers, 'manufacturer_id',
                'class = "inputbox" size = "1"', 'manufacturer_id', 'manufacturer_name');
            $smarty = smarty_init();
            $smarty->assign('list_categories', $list_categories);
            $smarty->assign('list_manufacturers', $list_manufacturers);
            $smarty->display('advanced_search.tpl');
        }
    }

    function showManufacturer($manufacturer_id, $limitstart)
    {
        global $mainframe, $unocartConfig, $Itemid;
        $database = &unocartFactory::getDBO();
        appendPathWay('manufacturer');
        $manufacturer = new unocartManufacturer($database);
        $manufacturer->load($manufacturer_id);
        $total = $manufacturer->getCountProducts();

        if (!$total) {
            echo _UNOCART_NO_MANUFACTURERS_PRODUCTS;
            return;
        }
        $limit = intval(($limit = mosGetParam($_REQUEST, 'limit', 0)) ? ($limit) : ($unocartConfig->
            count_products_to_page));
        // Formuvaty, chy ni ryadok navigation
        if ($total > $limit) {
            $products = $manufacturer->getProducts($limitstart, $limit);
            $link = ("index.php?option=com_unocart&task=manufacturers&manufacturer_id=" . $manufacturer_id .
                "&Itemid=" . $Itemid);
            require_once (JPATH_BASE . "/includes/pageNavigation.php");
            $pageNav = new mosPageNav($total, $limitstart, $limit);
            $pagenav = $pageNav->writePagesLinks($link);
            $show_pagenav = 1;
        } else {
            $products = $manufacturer->getProducts();
            $pagenav = '';
            $show_pagenav = 0;
        }
        addLinkToProducts($products);
        $smarty = smarty_init();
        $smarty->assign('no_image', 'no_image.gif');
        $smarty->assign('show_pagenav', $show_pagenav);
        $smarty->assign('navigation', $pagenav);
        $smarty->assign('count_product_to_row', $unocartConfig->count_products_to_row);
        $smarty->assign('products', $products);
        $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
        $smarty->assign('manufacturer', $manufacturer);
        $smarty->display('products_manufacturers.tpl');
    }

    function showAccount()
    {
        global $arr;
        checkUserLogin();
        $adv_user = getAdvInfoUser();
        $smarty = smarty_init();

        $smarty->assign('select_title', $arr['title']);
        $smarty->assign('user', $adv_user);
        $smarty->assign('href_edit_data', SEFLink('index.php?option=com_unocart&task=edit_account'));
        $smarty->assign('href_show_orders', SEFLink('index.php?option=com_unocart&task=orders'));

        $smarty->display('account.tpl');
    }

    function editAccount()
    {
        global $arr, $my;
        checkUserLogin();
        $smarty = smarty_init();
        $adv_user = getAdvInfoUser();

        $smarty->assign('select', $arr['title']);
        $option_country[] = mosHTML::makeOption(0, _UNOCART_REG_SELECT, 'country_id',
            'country_name');
        $select_countries = mosHTML::selectList(array_merge($option_country,
            unocartCountry::getAllCountries()), 'country',
            'id = "country" class = "inputbox" size = "1"', 'country_id', 'country_name', $adv_user->
            country);

        foreach ($arr['title'] as $key => $value) {
            $option_title[] = mosHTML::makeOption($key, $value, 'title_id', 'title_name');
        }
        $select_titles = mosHTML::selectList($option_title, 'title',
            'class = "inputbox" id = "title"', 'title_id', 'title_name', $adv_user->title);
        $select_d_titles = mosHTML::selectList($option_title, 'd_title',
            'class = "inputbox" id = "d_title"', 'title_id', 'title_name', $adv_user->
            d_title);

        $smarty->assign('select_countries', $select_countries);
        $smarty->assign('select_titles', $select_titles);
        $smarty->assign('select_d_titles', $select_d_titles);

        $smarty->assign('live_path', JPATH_SITE);
        $smarty->assign('adv_user', $adv_user);
        $smarty->assign('delivery_adress', $adv_user->delivery_adress);
        $smarty->assign('action', SEFLink('index.php?option=com_unocart&task=account'));
        $smarty->assign('register', 0);
        $smarty->assign('submit_text', _UNOCART_SAVE);
        $smarty->display('adress.tpl');
    }

    function saveAccount()
    {
        global $my;
        checkUserLogin();
        $database = &unocartFactory::getDBO();
        $user_shop = new unocartUser($database);
        $user_shop->load($my->id);
        $user_shop->bind($_POST);
        if (!$user_shop->check(1)) {
            echo "<script> alert('" . html_entity_decode($user_shop->getError()) .
                "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (!$user_shop->store()) {
            echo "<script> alert('" . html_entity_decode(_UNOCART_REGWARN_ERROR_DATABASE) .
                "'); window.history.go(-1); </script>\n";
            exit();
        }
        mosRedirect(SEFLink('index.php?option=com_unocart&task=account'));
    }

    function showOrders()
    {
        global $my, $unocartConfig;
        checkUserLogin();
        $orders = unocartOrder::getOrdersForUser($my->id);
        foreach ($orders as $key => $value) {
            $orders[$key]->order_href = SEFLink('index.php?option=com_unocart&task=order&order_id=' .
                $value->order_id);
        }
        $smarty = smarty_init();
        $smarty->assign('orders', $orders);
        $smarty->assign('image_path', $unocartConfig->live_path . "images");
        $smarty->display('show_orders.tpl');
    }

    function showOrder($order_id)
    {
        global $unocartConfig;
        checkUserLogin();
        $database = &unocartFactory::getDBO();
        $order = new unocartOrder($database);
        $order->load($order_id);
        $order->items = $order->getAllItems();
        $order->status_name = $order->getStatus();
        $order->history = $order->getHistory();
        $smarty = smarty_init();
        $smarty->assign('order', $order);
        $smarty->assign('image_path', $unocartConfig->live_path . "images");
        $smarty->display('show_order.tpl');
    }

    function showLastProducts($count)
    {
        global $unocartConfig;
        $rows = unocartProduct::getLastProducts($count);
        if (!count($rows))
            return;
        addLinkToProducts($rows);
        $smarty = smarty_init();
        $smarty->assign('lists_prod', $rows);
        $smarty->assign('count_product_to_row', $unocartConfig->count_products_to_row);
        $smarty->assign('image_product_path', $unocartConfig->image_product_live_path);
        $smarty->assign('no_image', 'no_image.gif');
        $smarty->display($template = 'last_products.tpl');
    }

    function downloadDemo($product_id)
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $product = new unocartProduct($database);
        $product->load($product_id);
        $file_name = $unocartConfig->files_path . $product->getDownloadFile();
        $fp = fopen($file_name, "rb");
        header("Cache-Control: ");
        header("Pragma: ");
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . (string )(filesize($file_name)));
        header('Content-Disposition: attachment; filename="' . basename($file_name) .
            '"');
        header("Content-Transfer-Encoding: binary\n");
        fpassthru($fp);
        exit();
    }

    function saveReview()
    {
        global $my;
        $database = &unocartFactory::getDBO();
        if (unocartReview::getAllowReview() <= 0) {
            echo unocartReview::getText();
            return;
        }
        $review = new unocartReview($database);
        $review->bind($_POST);
        $review->time = date("Y-m-d H:i:s", mktime());
        $review->user_id = $my->id;

        if (!$review->check()) {
            echo "error checking review";
            die();
        }
        if (!$review->store()) {
            echo "error saving to database";
            die();
        }
        mosRedirect(mosGetParam($_POST, 'back_link'));
    }

    function notifyPayment()
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $custom = mosGetParam($_POST, 'custom');
        $error = 0;
        if ($custom) {
            $database = &unocartFactory::getDBO();
            $query = "SELECT `order_id`
				  FROM `#__unocart_orders` AS orders
				  WHERE orders.order_hash = '" . $custom . "'";
            $database->setQuery($query);
            $order_id = $database->loadResult();
            if ($order_id) {
                $order = new unocartOrder($database);
                $order->load($order_id);
                $pm_method = new unocartPaymentMethod($database);
                $pm_method->load($order->payment_method_id);
            }
            if (!file_exists($unocartConfig->path . 'payments/' . $pm_method->payment_class .
                '.php')) {
                $error = 'File of payment method is missing. Order number: ' . $order->
                    order_number;
                mosMail($GLOBALS['mosConfig_mailfrom'], $GLOBALS['mosConfig_from'], $unocartConfig->
                    contact_email, 'Paypal payment', $error);
                return;
            } else {
                require_once ($unocartConfig->path . 'payments/' . $pm_method->payment_class .
                    '.php');
                require_once ($unocartConfig->path . 'payments/' . $pm_method->payment_class .
                    '_notify.php');
                $res = notify($order, $pm_method);
                $order_status_new = $res[1];
                if ($order->order_status != $order_status_new) {
                    $order->order_status = $order_status_new;
                    $order_status = new unocartOrderStatus($database);
                    $order_status->load($order_status_new);

                    $order_history = new unocartOrderHistory($database);
                    $order_history->order_id = $order->order_id;
                    $order_history->order_status_id = $order_status_new;
                    $order_history->status_date_added = date("Y-m-d H:i:s");

                    if ($res[0] === 1) {
                        // Successfull
                        $message = sprintf(_UNOCART_ORDER_STATUS_CHANGE, $order->order_number, $order_status->
                            status_name);
                        mosMail($GLOBALS['mosConfig_mailfrom'], $GLOBALS['mosConfig_from'], $unocartConfig->
                            contact_email, _UNOCART_ORDER_STATUS_CHANGE_TITLE, $message);
                        mosMail($GLOBALS['mosConfig_mailfrom'], $GLOBALS['mosConfig_from'], $order->
                            email, _UNOCART_ORDER_STATUS_CHANGE_TITLE, $message);
                        $order_history->customer_notify = 1;
                        $order_history->comments = '';

                    } else
                        if ($res[0] === -1) {
                            $message = sprintf(_UNOCART_ORDER_STATUS_CHANGE, $order->order_number, $order_status->
                                status_name) . "\n Status pending: " . $res[2];
                            mosMail($GLOBALS['mosConfig_mailfrom'], $GLOBALS['mosConfig_from'], $unocartConfig->
                                contact_email, _UNOCART_ORDER_STATUS_CHANGE_TITLE, $message);
                            $order_history->customer_notify = 0;
                            $order_history->comments = $res[2];
                        } else
                            if ($res[0] === 0) {
                                // Error with payment
                                $error = $res[2];
                                mosMail($GLOBALS['mosConfig_mailfrom'], $GLOBALS['mosConfig_from'], $unocartConfig->
                                    contact_email, _UNOCART_ERROR_PAYMENT, $error);
                                $order_history->customer_notify = 0;
                                $order_history->comments = $res[2];
                            }
                    $order_history->store();
                    $order->store();
                }
            }
        }
        die();
    }

    if ($option != 'com_unocart')
        return;
    switch ($task) {
        case 'new_products':
            showLastProducts($count = 20);
            break;
        case 'categories':
            showCategories($category_id, $limitstart);
            break;
        case 'add_to_cart':
            if (mosGetParam($_REQUEST, 'add_to_wishlist')) {
                $wishlist = new unocartWishList($database);
                $wishlist->add($product_id);
                showWishlist($wishlist);
            } else {
                $cart = new Cart;
                $cart->refreshCart(intval(mosGetParam($_REQUEST, 'product_id')), intval(mosGetParam
                    ($_REQUEST, 'quantity', 1)), mosGetParam($_REQUEST, 'act'), mosGetParam($_REQUEST,
                    'unocart_attr_id'));
                showCart();
            }
            break;
        case 'product':
            showProduct($product_id, $category_id);
            break;
        case 'cart':
            showCart();
            break;
        case 'checkout':
            JCheckout();
            break;
        case 'login':
            JLogin();
            break;
        case 'show_login':
            showLogin();
            break;
            /*
            case 'los_pass':
            JlostPassword();
            break;
            case 'send_new_pass':
            JsendNewPass();
            break;
            */
        case 'register':
            JRegister();
            break;
        case 'save_register':
            JsaveRegistration();
            break;
        case 'rabatt':
            JRabatt(mosGetParam($_REQUEST, 'rabatt'));
            break;
        case 'content':
            JContent(mosGetParam($_REQUEST, 'page'));
            break;
        case 'search':
            JSearch(mosGetParam($_REQUEST, 'unocart_search'), $limitstart);
            break;
        case 'adv_search':
            JAdvancedSearch(mosGetParam($_REQUEST, 'op'), mosGetParam($_REQUEST,
                'limitstart', 0));
            break;
        case 'manufacturers':
            showManufacturer(intval(mosGetParam($_REQUEST, 'manufacturer_id')), intval(mosGetParam
                ($_REQUEST, 'limitstart', 0)));
            break;
        case 'error':
            showError(mosGetParam($_REQUEST, 'error'));
            break;
        case 'wishlist':
            showWishList();
            break;
        case 'remove_from_wishlist':
            $wishlist = new unocartWishList($database);
            $wishlist->remove(intval(mosGetParam($_REQUEST, 'product_id')), $remove_from_cart =
                mosGetParam($_REQUEST, 'cart', ''));
            if ($remove_from_cart)
                showWishList();
            else
                showCart();
            break;
        case 'account':
            showAccount();
            break;
        case 'edit_account':
            editAccount();
            break;
        case 'save_account':
            saveAccount();
            break;
        case 'orders':
            showOrders();
            break;
        case 'order':
            showOrder(intval(mosGetParam($_REQUEST, 'order_id')));
            break;
        case 'd_demo':
            downloadDemo(intval(mosGetParam($_GET, 'product_id')));
            break;
        case 'save_review':
            saveReview();
            break;
        case 'notify':
            notifyPayment();
            break;
        default:
            showCategories(0, 0);
    }
    $mainframe->addCustomHeadTag('<link type = "text/css" rel = "stylesheet" href = "' .
        $unocartConfig->live_path . 'css/style_front.css" />');
    $mainframe->addCustomHeadTag('<script type = "text/javascript" src = "' . $mainframe->getCfg('live_site').'/includes/js/jquery/jquery.js"></script>');
    $mainframe->addCustomHeadTag('<script type = "text/javascript">jQuery.noConflict();</script>');
    $mainframe->addCustomHeadTag('<script type = "text/javascript" src = "' . $unocartConfig->
        live_path . 'js/jquery/jquery.media.js"></script>');
    $mainframe->addCustomHeadTag('<script type = "text/javascript" src = "' . $unocartConfig->
        live_path . 'js/functions.js"></script>');
    $mainframe->addCustomHeadTag('<script type = "text/javascript" src = "' . $unocartConfig->
        live_path . 'js/validateForm.js"></script>');
    $smarty = smarty_init();
    $smarty->display($template = 'copyright.tpl');
?>